package xjtu.zd.server.normal.login;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xjtu.zd.server.common.Result;
import xjtu.zd.server.common.TokenUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/normal/login")
public class LoginController {

    @Resource
    private LoginService loginService;

    @RequestMapping("")
    public Result login(@RequestBody LoginDto dto){

        String userId = loginService.findIdByPwd(dto);

        if(userId != null && userId != ""){
            String token = TokenUtils.loginSign(userId,dto.getU_pwd(),false);
            return Result.success((Object)token);
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"用户名或密码错误！");
    }

    @RequestMapping("/byemail")
    public Result loginByEmail(@RequestBody LoginDto dto){

        User user = loginService.findUserByEmail(dto);

        if(user == null){
            return Result.fail(Result.ERR_CODE_BUSINESS, "用户未注册！");
        }
        String token = TokenUtils.loginSign(user.getU_id(),user.getU_pwd(),false);
        return Result.success((Object)token);
    }

    @RequestMapping("/signup")
    public Result signUp(@RequestBody LoginDto dto){

        boolean confirm = loginService.checkSignUp(dto);

        if(confirm){
            loginService.addNewUser(dto);
            return Result.success("注册成功！");
        }

        return Result.fail(Result.ERR_CODE_BUSINESS,"用户名或邮箱重复！");

    }

    @RequestMapping("/password/reset")
    public Result resetPassword(@RequestBody LoginDto dto){
        dto.setU_pwd(loginService.DEFAULT_PASSWORD);
        loginService.resetPwd(dto);
        return Result.success("成功重置为初始密码！");
    }

}
